package com.xbe.netty;

import com.xbe.equipment.domain.Equipment;
import com.xbe.equipment.service.IEquipmentService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @date: 2019/10/8
 */
@Component
public class NettyServer
{
    private static final Logger log = LoggerFactory.getLogger("sys-user");

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private NettyServerHandler nettyServerHandler;


    @Autowired
    private IEquipmentService equipmentService;


    public void bind(int port)
    {


        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try
        {

            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler());


            ChannelFuture f = b.bind(port).sync();
            NettyServer.log.info("netty服务启动 启动端口【{}】", port);
            f.channel().closeFuture().sync();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        } finally
        {
            /**优雅退出，释放线程池资源*/
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public Set getSims()
    {
        Set sims = new HashSet();
        List<Equipment> equipmentList = equipmentService.getSims();
        for (Equipment equipment : equipmentList)
        {
            sims.add(equipment.getSim().trim());

        }
        return sims;
    }


    private class ChildChannelHandler extends ChannelInitializer<SocketChannel>
    {
        @Override
        protected void initChannel(SocketChannel socketChannel)
        {
            socketChannel.pipeline().addLast(nettyServerHandler);
            socketChannel.pipeline().addLast(new StringDecoder());
            socketChannel.pipeline().addLast(new StringEncoder());
        }
    }
}
